import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/market_model/market_incubation_list_model.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_rob_buy/market_rob_buy_controller.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_rob_buy/rob_window_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/transaction_password_page.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/checkbox_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:oktoast/oktoast.dart';

class HeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  double get minExtent => 50.px;

  @override
  double get maxExtent => 50.px;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    MarketRobBuyController controller = Get.find();
    return Container(
      width: context.width,
      height: 50.px,
      padding: EdgeInsets.fromLTRB(18.px, 12.px, 18.px, 12.px),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(18.px),
          topRight: Radius.circular(18.px),
        ),
        gradient: LinearGradient(
          colors: [
            Color.fromRGBO(31, 33, 38, 1),
            Color.fromRGBO(30, 33, 38, 0),
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                '选择藏品',
                style: TextStyle(fontSize: 14.px, color: AppColors.fontColor),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}

class MarketRobBuyPage extends GetView<MarketRobBuyController>
    implements PreferredSizeWidget {
  static const String path = '/MarketRobBuyPage';
  const MarketRobBuyPage({super.key});
  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      bottomNavigationBar: _bottomBuy(context: context),
      body: SafeArea(
        top: false,
        child: Scaffold(
          body: Obx(() {
            return RefreshIndicator(
              backgroundColor: Colors.transparent,
              color: Colors.white,
              onRefresh: controller.handleRefresh,
              child: Container(
                decoration: BoxDecoration(
                  color: AppColors.backgroundColorBlack,
                ),
                child: Stack(
                  children: [
                       Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),
                    CustomScrollView(
                      physics: AlwaysScrollableScrollPhysics(),
                      controller: controller.scrollController,
                      slivers: [
                        SliverToBoxAdapter(
                          child: Stack(
                            children: [
                              Padding(
                                padding: EdgeInsets.fromLTRB(
                                  0.px,
                                  top,
                                  0.px,
                                  0,
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    CustomAppBar2(
                                      title: '${controller.hradTitle}',
                                      context: context,
                                    ),
                                    Text(
                                      '${controller.count}${controller.listChoose.length}',
                                      style: TextStyle(
                                        fontSize: 0,
                                        color: AppColors.backgroundColor,
                                      ),
                                    ),
                                    _walletHead(context: context),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        SliverPersistentHeader(
                          delegate: HeaderDelegate(),
                          pinned: true,
                        ),
                        SliverPadding(
                          padding: EdgeInsets.fromLTRB(
                            12.px,
                            12.px,
                            12.px,
                            12.px,
                          ),
                          sliver: SliverGrid(
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3,
                                  crossAxisSpacing: 8.px,
                                  mainAxisSpacing: 8.px,
                                  childAspectRatio: 112.px / 176.px,
                                ),
                            delegate: SliverChildBuilderDelegate(
                              childCount: controller.list.length,
                              (BuildContext context, int index) {
                                return LayoutBuilder(
                                  builder: (
                                    BuildContext context,
                                    BoxConstraints constraints,
                                  ) {
                                    return _listItemUnSale(
                                      item: controller.list[index],
                                      context: context,
                                      constraints: constraints,
                                      index: index,
                                    );
                                  },
                                );
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          }),
        ),
      ),
    );
  }

  _walletHead({required BuildContext context}) {
    return Center(
      child: Container(
        width: 351.px,
        padding: EdgeInsets.fromLTRB(18.px, 14.px, 18.px, 20.px),
        margin: EdgeInsets.fromLTRB(0, 20.px, 0, 20.px),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.px),
          color: AppColors.backgroundColorGrey2,
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '可用余额',
              style: TextStyle(
                fontSize: 16.px,
                color: AppColors.backgroundColorGrey,
              ),
            ),
            SizedBox(height: 21.px),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  '${controller.hasWallet.value}',
                  style: TextStyle(fontSize: 24.px, color: AppColors.fontColor),
                ),
                ButtonWidget(
                  label: '充值',
                  width: 68.px,
                  height: 27.px,
                  borderRadius: 6,
                  fontSize: 12.px,
                  onPressed: () {
                    controller.investmoney();
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  _listItemUnSale({
    required MarketIncubationListModelItem item,
    required BuildContext context,
    required BoxConstraints constraints,
    required int index,
  }) {
    return GestureDetector(
      onTap: () {
        controller.chooseListSell(item.collectionId);
      },
      child: Stack(
        children: [
          Container(
            // width: (constraints.maxWidth -2.px),
            // height: (constraints.maxHeight -2.px),
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(
              // color: AppColors.startColor,
              border: Border.all(
                width: 1.px,
                color:
                    item.isSelect == true
                        ? AppColors.startColor
                        : Color.fromRGBO(255, 255, 255, 0.1),
              ),
              borderRadius: BorderRadius.circular(8.px),
              color: AppColors.backgroundColorBlackLight,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  clipBehavior: Clip.antiAlias,
                  height: 114.px,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(8.px),
                      topRight: Radius.circular(8.px),
                    ),
                  ),
                  width: (constraints.maxWidth - 2.px),
                  child: LazyImage(
                    imageUrl: '${item.coverImageUrl}',
                    height: 114.px,
                    width: (constraints.maxWidth - 2.px),
                    borderRadius: 0,
                  ),
                ),
                SizedBox(height: 8.px),
                Container(
                  width: (constraints.maxWidth - 2.px),
                  padding: EdgeInsets.only(left: 8.px, right: 8.px),
                  child: Text(
                    '${item.collectionName}',
                    style: TextStyle(
                      fontSize: 13.px,
                      color: AppColors.backgroundColor,
                    ),
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  width: (constraints.maxWidth - 2.px),
                  padding: EdgeInsets.only(left: 8.px, right: 8.px),
                  child: Row(
                    children: [
                      Text(
                        '￥',
                        style: TextStyle(
                          fontSize: 14.px,
                          color: AppColors.startColor,
                        ),
                        textAlign: TextAlign.left,
                      ),
                      Text(
                        '${item.totalPriceLimit}',
                        style: TextStyle(
                          fontSize: 20.px,
                          color: AppColors.startColor,
                        ),
                        textAlign: TextAlign.left,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          if (item.isSelect == true)
            Positioned(
              top: 9.px,
              right: 9.px,
              child: ImageAssetWidget(
                width: 16.px,
                height: 16.px,
                imageUrl: 'static/images/active_check.png',
              ),
            ),
        ],
      ),
    );
  }

  _bottomBuy({required BuildContext context}) {
    return Container(
      width: context.width,
      height: 60.px,
      margin: EdgeInsets.only(top: 10.px, bottom: 10.px),
      decoration: BoxDecoration(color: Color.fromRGBO(31, 33, 38, 1)),
      padding: EdgeInsets.only(
        left: 16.px,
        right: 14.px,
        top: 10.px,
        bottom: 10.px,
      ),
      child: Obx(() {
        return Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                children: [
                  CheckboxWidget(
                    onChanged: (val) {
                      controller.isAllSelect.value = val;
                      controller.selectAll();
                    },
                    checked: controller.isAllSelect.value,
                  ),
                  hiSpace(width: 6.px),
                  Text(
                    '全选',
                    style: TextStyle(
                      fontSize: 14.px,
                      color: AppColors.fontColor,
                    ),
                    textAlign: TextAlign.left,
                  ),
                  hiSpace(width: 12.px),
                  RichText(
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    text: TextSpan(
                      children: <TextSpan>[
                        TextSpan(
                          text: '已选 ',
                          style: TextStyle(
                            color: AppColors.fontColor,
                            fontSize: 12.px,
                          ),
                        ),
                        TextSpan(
                          text: ' ${controller.listChoose.length}',
                          style: TextStyle(
                            color: AppColors.fontColorSearch,
                            fontSize: 12.px,
                          ),
                        ),
                        TextSpan(
                          text: '/${controller.list.length}',
                          style: TextStyle(
                            color: AppColors.fontColor,
                            fontSize: 12.px,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),

              GestureDetector(
                onTap: () {
                  if (controller.title.value == '校验交易密码') {
                    if (controller.listChoose.isEmpty) {
                      showToast('请选择至少一种藏品');
                      return;
                    }
                    final GlobalController globalController = Get.find();
                    if (globalController.user.value!.isSm != true) {
                      controller.toSm(context: context);
                      return;
                    }
                    if (globalController.user.value?.transactionPassword ==
                        null) {
                      controller.isSetPayPassword();
                      return;
                    }
                    controller.rightTxt.value = '暂停抢购';
                    TransactionPasswordDialog.show(
                      Get.context!,
                      onCompleted: (password) {
                        controller.password.value = password;
                        controller.verifySecurityPassword((res) {
                          if (res == true) {
                            controller.title.value = '立即抢购';
                          }
                        });
                      },
                      onCancel: () {
                        // 取消回调（可选）
                        controller.password.value = '';
                      },
                    );
                  } else {
                    // var hasMoney = false;
                    // controller.listChoose.forEach((element) {
                    //   if (double.parse(element.totalPriceLimit) <=
                    //       double.parse(controller.hasWallet.value)) {
                    //     hasMoney = true;
                    //   }
                    // });
                    // if (!hasMoney) {
                    //   showToast('余额不足，请充值');
                    //   return;
                    // }
                    RobWindowPage.show(
                      Get.context!,
                      onCompleted: (finish) {
                        // consoleLog('关闭弹窗');
                      },
                      onCancel: () {
                        // consoleLog('关闭弹窗右边');
                        controller.title.value = '校验交易密码';
                      },
                    );
                  }
                },
                child: Container(
                  width: 162.px,
                  height: 40.px,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(100),
                    gradient: LinearGradient(
                      colors: [
                        AppColors.startColor,
                        AppColors.endColor,
                      ], // 定义渐变颜色
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                    ),
                  ),
                  child: Center(
                    child: Text(
                      '${controller.title}',
                      style: TextStyle(
                        color: AppColors.backgroundColorBlack,
                        fontWeight: FontWeight.bold,
                        fontSize: 15.px,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }),
    );
  }
}
